
import smtplib
from balancer import BalanceAccount

class RefreshListener:
    """Base class for listeners that are updated when a refresh occurs."""

    def refreshed(self, results):
        pass

class RefreshDescription:
    """Describes the nature of a refresh."""

    def __init__(self, fromUi=False, fromScheduler=False):
        self.__fromUi = fromUi
        self.__fromScheduler = fromScheduler


    def is_from_ui(self):
        return self.__fromUi

    def is_from_scheduler(self):
        return self.__fromScheduler

class HistoryRefreshListener(RefreshListener):
    """Writes the refresh history to disk."""

    def __init__(self, gm):
        self.__gm = gm


    def refreshed(self, results, desc):
        """Informs the listener that a refresh has occured."""
        self.__gm.get_historian().add_run(results, desc)


class SmsRefreshListener(RefreshListener):
    """Emails the given address an SMS message for a refresh."""

    def __init__(self, gm):
        self.__gm = gm


    def refreshed(self, results, desc):
        
        filter = self.__gm.get_email_notification_filter()
        balances = filter.filter(results)

        def group(number):
            """From http://stackoverflow.com/questions/1823058/how-to-print-number-with-commas-as-thousands-separators-in-python-2-x"""
            s = '%d' % number
            groups = []
            while s and s[-1].isdigit():
                groups.append(s[-3:])
                s = s[:-3]
            return s + ','.join(reversed(groups))

        text = "\r\nBalance: \r\n"
        for balance in balances.get_accounts():
            cash = int(float(balance.get_balance()))
            if balance.get_type() == BalanceAccount.CREDIT_CARD:
                cash = cash * -1
            text = text + " ~ " + balance.get_name() + ": $" + group(cash) + "\r\n"

        conf = self.__gm.get_email_notification()

        s = smtplib.SMTP(conf['server'], conf['port'])
        s.set_debuglevel(1)
        r = s.ehlo()
        if r[1].find("STARTTLS") > -1:
            s.starttls()
    
        s.login(conf["from"], conf["password"])
        s.sendmail(conf["from"], [conf["to"]], text)
        s.quit()
